Skip to content

Fix EH clause sort to handle try-in-handler nesting#8428

Open
bouwkast wants to merge 5 commits intomasterfrom
steven/attempt-fix-invalid-program-exception
Open

Fix EH clause sort to handle try-in-handler nesting#8428
bouwkast wants to merge 5 commits intomasterfrom
steven/attempt-fix-invalid-program-exception

Conversation

@bouwkast
Copy link
Copy Markdown
Collaborator

@bouwkast bouwkast commented Apr 8, 2026

Generated mostly by Claude

Summary of changes

Fix incorrect EH clause ordering in ILRewriter::Export() that caused InvalidProgramException when instrumenting methods with try blocks nested inside handler regions.

Reason for change

When we instrument a method, the IL rewriter may insert try/catch blocks inside the handler of an existing try/catch (e.g., debugger inserting EndMethod(SetException) inside an async state machine's outer catch, or CallTarget instrumentation wrapping handler logic). ECMA-335 II.19 requires such nested clauses to appear before the clause whose region encloses them in the EH table.

The existing sort comparator only checked try-in-try containment:

return a.m_pTryBegin->m_offset > b.m_pTryBegin->m_offset &&
       a.m_pTryEnd->m_offset < b.m_pTryEnd->m_offset;

Because the inserted clause's try region starts after the outer clause's try region ends, this check returns false. The clause stays in its appended position -- after the outer clause -- violating ECMA-335. The CLR validates EH table ordering on JIT and rejects the method with InvalidProgramException.

The comparator also violated strict weak ordering required by std::sort (transitivity of incomparability fails for sibling clauses adjacent to a nesting relationship), making its behavior undefined.

Implementation details

Replaced the inline std::sort with ILRewriter::SortEHClauses, a new static method that:

  1. Computes a nesting depth for each clause: the number of other clauses whose try or handler region strictly contains this clause's try region. This correctly detects both try-in-try and try-in-handler nesting per ECMA-335 II.19.

  2. Sorts by (depth descending, try offset ascending), which is a total order and therefore satisfies strict weak ordering. Deeper-nested clauses sort first, satisfying the ECMA-335 requirement.

The method is extracted as a static to make it directly unit-testable without requiring ICorProfilerInfo. Internal allocations use std::unique_ptr to prevent memory leaks if an allocation fails.

Test coverage

Added ILRewriterEHSortTest in Datadog.Tracer.Native.Tests with 8 Google Test cases covering:

  • Try-in-try nesting (existing behavior preserved)
  • Try-in-handler nesting (the core bug)
  • Sibling clauses (no nesting constraint, ordered by offset)
  • Three-level deep nesting
  • The exact debugger async middleware topology: 2 original Roslyn clauses + 3 debugger-inserted clauses, verifying the EndMethod(SetException) clause is ordered before the outer clause whose handler contains it
  • Single and zero clause edge cases

The OldComparatorFailsMiddlewareScenario test applies the original comparator inline against the middleware topology and asserts it produces the wrong ordering, confirming the bug is real and the new tests would catch a regression.

Added integration test in tracer/test/test-applications/integrations/Samples.TraceAnnotations/ExtremeExceptionHandling.cs that reproduces the crash. Without the fix, the test causes a CLR fatal exception.

Other details

Symptom: System.InvalidProgramException: Common Language Runtime detected an invalid program thrown on any instrumented method whose EH table contains try-in-handler nesting. Originally observed on async middleware InvokeAsync methods with Exception Replay enabled, but affects any instrumentation path that goes through ILRewriter::Export().

Linked to APMS-19196

@pr-commenter
Copy link
Copy Markdown

pr-commenter bot commented Apr 8, 2026

Benchmarks

Benchmark execution time: 2026-04-10 16:42:25

Comparing candidate commit 6b6b9a4 in PR branch steven/attempt-fix-invalid-program-exception with baseline commit 58f22e8 in branch master.

Found 29 performance improvements and 40 performance regressions! Performance is the same for 211 metrics, 8 unstable metrics.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

scenario:Benchmarks.Trace.ActivityBenchmark.StartStopWithChild net6.0

  • 🟩 throughput [+9548.628op/s; +11764.432op/s] or [+8.026%; +9.888%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces net472

  • 🟥 execution_time [+310.313ms; +312.244ms] or [+153.988%; +154.947%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces net6.0

  • 🟥 execution_time [+383.460ms; +385.932ms] or [+302.957%; +304.910%]

scenario:Benchmarks.Trace.AgentWriterBenchmark.WriteAndFlushEnrichedTraces netcoreapp3.1

  • 🟥 execution_time [+399.125ms; +400.869ms] or [+353.210%; +354.754%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleMoreComplexBody net6.0

  • 🟩 throughput [+7020.530op/s; +10689.119op/s] or [+5.125%; +7.802%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleSimpleBody net6.0

  • 🟩 execution_time [-25.684ms; -20.320ms] or [-11.454%; -9.062%]
  • 🟩 throughput [+94044.821op/s; +118851.855op/s] or [+10.047%; +12.697%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.AllCycleSimpleBody netcoreapp3.1

  • 🟩 throughput [+80818.848op/s; +104600.396op/s] or [+11.612%; +15.029%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorMoreComplexBody net6.0

  • 🟩 throughput [+9575.256op/s; +12510.799op/s] or [+6.093%; +7.960%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorSimpleBody net6.0

  • 🟩 throughput [+334472.210op/s; +368839.400op/s] or [+11.153%; +12.299%]

scenario:Benchmarks.Trace.Asm.AppSecBodyBenchmark.ObjectExtractorSimpleBody netcoreapp3.1

  • 🟩 execution_time [-18.174ms; -13.750ms] or [-8.377%; -6.338%]
  • 🟩 throughput [+171719.940op/s; +227626.727op/s] or [+6.816%; +9.035%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs net472

  • 🟥 execution_time [+300.389ms; +300.923ms] or [+150.094%; +150.361%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs net6.0

  • 🟥 execution_time [+298.337ms; +301.534ms] or [+150.452%; +152.064%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeArgs netcoreapp3.1

  • 🟥 execution_time [+299.562ms; +302.086ms] or [+150.896%; +152.168%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs net472

  • 🟥 execution_time [+297.909ms; +298.802ms] or [+146.321%; +146.760%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs net6.0

  • 🟥 execution_time [+293.783ms; +294.930ms] or [+143.620%; +144.180%]

scenario:Benchmarks.Trace.Asm.AppSecEncoderBenchmark.EncodeLegacyArgs netcoreapp3.1

  • 🟥 execution_time [+300.637ms; +301.889ms] or [+150.258%; +150.884%]

scenario:Benchmarks.Trace.Asm.AppSecWafBenchmark.RunWafRealisticBenchmark net6.0

  • 🟥 execution_time [+23.102µs; +50.059µs] or [+5.299%; +11.481%]
  • 🟥 throughput [-243.374op/s; -122.248op/s] or [-10.581%; -5.315%]

scenario:Benchmarks.Trace.Asm.AppSecWafBenchmark.RunWafRealisticBenchmarkWithAttack net6.0

  • 🟥 execution_time [+27.424µs; +51.122µs] or [+8.755%; +16.321%]
  • 🟥 throughput [-469.477op/s; -270.270op/s] or [-14.635%; -8.425%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest net472

  • 🟥 execution_time [+299.785ms; +300.491ms] or [+149.624%; +149.976%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest net6.0

  • 🟥 execution_time [+416.064ms; +422.385ms] or [+452.071%; +458.938%]
  • 🟩 throughput [+1205.948op/s; +1340.391op/s] or [+9.909%; +11.014%]

scenario:Benchmarks.Trace.AspNetCoreBenchmark.SendRequest netcoreapp3.1

  • 🟩 throughput [+722.025op/s; +922.288op/s] or [+6.990%; +8.928%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces net472

  • 🟥 throughput [-534.901op/s; -471.858op/s] or [-48.467%; -42.755%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces net6.0

  • 🟥 throughput [-746.267op/s; -662.807op/s] or [-49.776%; -44.209%]

scenario:Benchmarks.Trace.CIVisibilityProtocolWriterBenchmark.WriteAndFlushEnrichedTraces netcoreapp3.1

  • 🟥 execution_time [+345.433ms; +355.347ms] or [+206.609%; +212.539%]
  • 🟥 throughput [-420.184op/s; -384.657op/s] or [-29.257%; -26.783%]

scenario:Benchmarks.Trace.CharSliceBenchmark.OriginalCharSlice net6.0

  • 🟩 execution_time [-178.341µs; -140.258µs] or [-9.034%; -7.105%]
  • 🟩 throughput [+40.713op/s; +50.970op/s] or [+8.037%; +10.062%]

scenario:Benchmarks.Trace.DbCommandBenchmark.ExecuteNonQuery net472

  • 🟥 throughput [-23191.121op/s; -19323.832op/s] or [-6.532%; -5.443%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch net472

  • 🟥 execution_time [+302.404ms; +303.410ms] or [+152.285%; +152.791%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch net6.0

  • 🟥 execution_time [+301.289ms; +302.371ms] or [+150.977%; +151.519%]
  • 🟩 throughput [+45266.743op/s; +49316.963op/s] or [+7.137%; +7.775%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearch netcoreapp3.1

  • 🟥 execution_time [+301.699ms; +305.120ms] or [+151.561%; +153.280%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync net472

  • 🟥 execution_time [+302.800ms; +304.724ms] or [+152.056%; +153.022%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync net6.0

  • 🟥 execution_time [+298.693ms; +300.194ms] or [+147.690%; +148.432%]

scenario:Benchmarks.Trace.ElasticsearchBenchmark.CallElasticsearchAsync netcoreapp3.1

  • 🟥 execution_time [+300.640ms; +304.226ms] or [+152.377%; +154.195%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync net472

  • 🟥 execution_time [+301.799ms; +302.946ms] or [+151.476%; +152.052%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync net6.0

  • 🟥 execution_time [+296.347ms; +298.983ms] or [+147.702%; +149.016%]
  • 🟩 throughput [+59952.851op/s; +65420.563op/s] or [+11.905%; +12.990%]

scenario:Benchmarks.Trace.GraphQLBenchmark.ExecuteAsync netcoreapp3.1

  • 🟥 execution_time [+300.411ms; +303.589ms] or [+149.452%; +151.033%]

scenario:Benchmarks.Trace.HttpClientBenchmark.SendAsync net472

  • 🟥 throughput [-5761.819op/s; -5063.798op/s] or [-6.578%; -5.781%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatAspectBenchmark net6.0

  • 🟩 allocated_mem [-18.656KB; -18.635KB] or [-6.805%; -6.798%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatAspectBenchmark netcoreapp3.1

  • 🟩 throughput [+99.344op/s; +253.816op/s] or [+5.676%; +14.501%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatBenchmark net6.0

  • 🟥 throughput [-5474.955op/s; -3622.521op/s] or [-23.048%; -15.250%]

scenario:Benchmarks.Trace.Iast.StringAspectsBenchmark.StringConcatBenchmark netcoreapp3.1

  • 🟩 throughput [+2016.093op/s; +3444.264op/s] or [+12.369%; +21.132%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog net472

  • 🟥 execution_time [+299.678ms; +302.643ms] or [+151.474%; +152.972%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog net6.0

  • 🟥 execution_time [+304.499ms; +307.867ms] or [+154.989%; +156.703%]

scenario:Benchmarks.Trace.Log4netBenchmark.EnrichedLog netcoreapp3.1

  • 🟥 execution_time [+299.461ms; +301.354ms] or [+149.917%; +150.865%]

scenario:Benchmarks.Trace.RedisBenchmark.SendReceive net472

  • 🟥 throughput [-26477.882op/s; -23444.148op/s] or [-7.330%; -6.490%]

scenario:Benchmarks.Trace.RedisBenchmark.SendReceive net6.0

  • 🟩 throughput [+51690.348op/s; +55979.220op/s] or [+9.784%; +10.596%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog net472

  • 🟥 execution_time [+298.726ms; +300.432ms] or [+148.888%; +149.738%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog net6.0

  • 🟥 execution_time [+301.125ms; +303.168ms] or [+151.210%; +152.237%]

scenario:Benchmarks.Trace.SerilogBenchmark.EnrichedLog netcoreapp3.1

  • 🟥 execution_time [+302.786ms; +305.195ms] or [+153.554%; +154.776%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore net472

  • 🟥 execution_time [+299.550ms; +300.164ms] or [+149.417%; +149.723%]
  • 🟩 throughput [+54901288.039op/s; +62548025.776op/s] or [+39.983%; +45.551%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore net6.0

  • 🟩 throughput [+1033.824op/s; +1199.149op/s] or [+7.992%; +9.270%]

scenario:Benchmarks.Trace.SingleSpanAspNetCoreBenchmark.SingleSpanAspNetCore netcoreapp3.1

  • 🟥 execution_time [+299.077ms; +300.035ms] or [+149.173%; +149.651%]
  • 🟩 throughput [+18122197.279op/s; +19068456.892op/s] or [+8.027%; +8.446%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishScope net6.0

  • 🟩 throughput [+89904.419op/s; +101443.105op/s] or [+8.394%; +9.471%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishScope netcoreapp3.1

  • 🟩 throughput [+48303.976op/s; +67554.697op/s] or [+5.591%; +7.819%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishSpan net6.0

  • 🟩 throughput [+84967.580op/s; +114987.256op/s] or [+6.577%; +8.900%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishSpan netcoreapp3.1

  • 🟩 throughput [+92101.518op/s; +100014.464op/s] or [+9.147%; +9.933%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishTwoScopes net6.0

  • 🟩 throughput [+52067.984op/s; +56960.378op/s] or [+9.455%; +10.343%]

scenario:Benchmarks.Trace.SpanBenchmark.StartFinishTwoScopes netcoreapp3.1

  • 🟩 throughput [+24274.776op/s; +34122.632op/s] or [+5.433%; +7.638%]

scenario:Benchmarks.Trace.TraceAnnotationsBenchmark.RunOnMethodBegin net6.0

  • 🟩 throughput [+74958.066op/s; +92858.306op/s] or [+8.375%; +10.375%]

@bouwkast
Copy link
Copy Markdown
Collaborator Author

bouwkast commented Apr 8, 2026

Closing this as I just thought it would be easier to share this as a PR form than not, if this is valuable can always pick it back up but we don't know if this actually solves anything.

@bouwkast bouwkast closed this Apr 8, 2026
@bouwkast bouwkast reopened this Apr 9, 2026
@dd-trace-dotnet-ci-bot
Copy link
Copy Markdown

dd-trace-dotnet-ci-bot bot commented Apr 9, 2026

Execution-Time Benchmarks Report ⏱️

Execution-time results for samples comparing This PR (8428) and master.

✅ No regressions detected - check the details below

Full Metrics Comparison

FakeDbCommand

Metric Master (Mean ± 95% CI) Current (Mean ± 95% CI) Change Status
.NET Framework 4.8 - Baseline
duration71.72 ± (71.73 - 72.12) ms72.34 ± (72.30 - 72.66) ms+0.9%✅⬆️
.NET Framework 4.8 - Bailout
duration76.00 ± (75.95 - 76.33) ms76.59 ± (76.31 - 76.68) ms+0.8%✅⬆️
.NET Framework 4.8 - CallTarget+Inlining+NGEN
duration1060.87 ± (1061.33 - 1066.65) ms1068.83 ± (1069.20 - 1075.28) ms+0.8%✅⬆️
.NET Core 3.1 - Baseline
process.internal_duration_ms22.07 ± (22.04 - 22.11) ms22.42 ± (22.37 - 22.47) ms+1.6%✅⬆️
process.time_to_main_ms83.06 ± (82.88 - 83.24) ms84.03 ± (83.81 - 84.26) ms+1.2%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.91 ± (10.91 - 10.92) MB10.91 ± (10.91 - 10.91) MB-0.1%
runtime.dotnet.threads.count12 ± (12 - 12)12 ± (12 - 12)+0.0%
.NET Core 3.1 - Bailout
process.internal_duration_ms22.17 ± (22.13 - 22.22) ms22.44 ± (22.39 - 22.48) ms+1.2%✅⬆️
process.time_to_main_ms84.78 ± (84.59 - 84.96) ms85.61 ± (85.43 - 85.80) ms+1.0%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.94 ± (10.93 - 10.94) MB10.93 ± (10.92 - 10.93) MB-0.1%
runtime.dotnet.threads.count13 ± (13 - 13)13 ± (13 - 13)+0.0%
.NET Core 3.1 - CallTarget+Inlining+NGEN
process.internal_duration_ms226.59 ± (225.34 - 227.85) ms226.25 ± (225.12 - 227.38) ms-0.2%
process.time_to_main_ms519.53 ± (518.17 - 520.89) ms522.49 ± (521.49 - 523.50) ms+0.6%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed48.50 ± (48.47 - 48.54) MB48.44 ± (48.40 - 48.47) MB-0.1%
runtime.dotnet.threads.count28 ± (28 - 28)28 ± (28 - 28)+0.0%
.NET 6 - Baseline
process.internal_duration_ms20.92 ± (20.88 - 20.96) ms21.15 ± (21.12 - 21.19) ms+1.1%✅⬆️
process.time_to_main_ms71.99 ± (71.77 - 72.21) ms72.97 ± (72.80 - 73.14) ms+1.4%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.60 ± (10.60 - 10.61) MB10.61 ± (10.61 - 10.61) MB+0.1%✅⬆️
runtime.dotnet.threads.count10 ± (10 - 10)10 ± (10 - 10)+0.0%
.NET 6 - Bailout
process.internal_duration_ms21.03 ± (20.99 - 21.06) ms20.95 ± (20.91 - 20.99) ms-0.4%
process.time_to_main_ms74.00 ± (73.82 - 74.18) ms73.55 ± (73.41 - 73.70) ms-0.6%
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed10.72 ± (10.72 - 10.72) MB10.73 ± (10.73 - 10.73) MB+0.1%✅⬆️
runtime.dotnet.threads.count11 ± (11 - 11)11 ± (11 - 11)+0.0%
.NET 6 - CallTarget+Inlining+NGEN
process.internal_duration_ms385.78 ± (383.58 - 387.97) ms386.72 ± (384.34 - 389.10) ms+0.2%✅⬆️
process.time_to_main_ms521.41 ± (520.51 - 522.31) ms520.11 ± (519.28 - 520.94) ms-0.2%
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed49.97 ± (49.94 - 50.00) MB49.97 ± (49.95 - 50.00) MB+0.0%✅⬆️
runtime.dotnet.threads.count28 ± (28 - 28)28 ± (28 - 28)-0.2%
.NET 8 - Baseline
process.internal_duration_ms19.17 ± (19.14 - 19.20) ms19.19 ± (19.16 - 19.23) ms+0.1%✅⬆️
process.time_to_main_ms71.37 ± (71.22 - 71.52) ms71.42 ± (71.23 - 71.60) ms+0.1%✅⬆️
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed7.68 ± (7.68 - 7.69) MB7.66 ± (7.65 - 7.66) MB-0.3%
runtime.dotnet.threads.count10 ± (10 - 10)10 ± (10 - 10)+0.0%
.NET 8 - Bailout
process.internal_duration_ms19.26 ± (19.23 - 19.29) ms19.09 ± (19.06 - 19.13) ms-0.9%
process.time_to_main_ms72.65 ± (72.51 - 72.79) ms71.84 ± (71.68 - 72.00) ms-1.1%
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed7.74 ± (7.73 - 7.75) MB7.71 ± (7.71 - 7.72) MB-0.3%
runtime.dotnet.threads.count11 ± (11 - 11)11 ± (11 - 11)+0.0%
.NET 8 - CallTarget+Inlining+NGEN
process.internal_duration_ms306.84 ± (304.38 - 309.30) ms303.55 ± (301.14 - 305.96) ms-1.1%
process.time_to_main_ms479.28 ± (478.55 - 480.00) ms477.99 ± (477.18 - 478.79) ms-0.3%
runtime.dotnet.exceptions.count0 ± (0 - 0)0 ± (0 - 0)+0.0%
runtime.dotnet.mem.committed37.13 ± (37.11 - 37.16) MB37.11 ± (37.09 - 37.14) MB-0.0%
runtime.dotnet.threads.count27 ± (27 - 27)27 ± (27 - 27)-0.4%

HttpMessageHandler

Metric Master (Mean ± 95% CI) Current (Mean ± 95% CI) Change Status
.NET Framework 4.8 - Baseline
duration200.07 ± (200.22 - 201.10) ms201.03 ± (200.89 - 201.65) ms+0.5%✅⬆️
.NET Framework 4.8 - Bailout
duration203.73 ± (203.43 - 203.95) ms203.90 ± (203.74 - 204.27) ms+0.1%✅⬆️
.NET Framework 4.8 - CallTarget+Inlining+NGEN
duration1178.52 ± (1178.82 - 1185.62) ms1175.57 ± (1173.56 - 1179.41) ms-0.2%
.NET Core 3.1 - Baseline
process.internal_duration_ms194.80 ± (194.45 - 195.14) ms195.73 ± (195.35 - 196.12) ms+0.5%✅⬆️
process.time_to_main_ms83.91 ± (83.73 - 84.09) ms84.50 ± (84.25 - 84.74) ms+0.7%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed16.10 ± (16.07 - 16.13) MB16.05 ± (16.03 - 16.07) MB-0.3%
runtime.dotnet.threads.count20 ± (19 - 20)20 ± (19 - 20)+0.1%✅⬆️
.NET Core 3.1 - Bailout
process.internal_duration_ms194.02 ± (193.71 - 194.32) ms194.98 ± (194.66 - 195.30) ms+0.5%✅⬆️
process.time_to_main_ms85.14 ± (85.00 - 85.29) ms85.52 ± (85.36 - 85.67) ms+0.4%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed16.04 ± (16.02 - 16.07) MB16.17 ± (16.14 - 16.19) MB+0.8%✅⬆️
runtime.dotnet.threads.count21 ± (20 - 21)21 ± (20 - 21)-0.1%
.NET Core 3.1 - CallTarget+Inlining+NGEN
process.internal_duration_ms404.71 ± (403.27 - 406.16) ms406.49 ± (405.14 - 407.83) ms+0.4%✅⬆️
process.time_to_main_ms527.16 ± (526.07 - 528.24) ms529.82 ± (528.58 - 531.07) ms+0.5%✅⬆️
runtime.dotnet.exceptions.count3 ± (3 - 3)3 ± (3 - 3)+0.0%
runtime.dotnet.mem.committed59.26 ± (59.20 - 59.31) MB59.17 ± (59.11 - 59.23) MB-0.1%
runtime.dotnet.threads.count30 ± (30 - 30)30 ± (30 - 30)+0.2%✅⬆️
.NET 6 - Baseline
process.internal_duration_ms200.93 ± (200.57 - 201.29) ms200.66 ± (200.25 - 201.07) ms-0.1%
process.time_to_main_ms73.72 ± (73.53 - 73.92) ms73.35 ± (73.15 - 73.54) ms-0.5%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed16.32 ± (16.29 - 16.35) MB16.33 ± (16.30 - 16.35) MB+0.0%✅⬆️
runtime.dotnet.threads.count19 ± (19 - 19)19 ± (19 - 19)+0.2%✅⬆️
.NET 6 - Bailout
process.internal_duration_ms199.59 ± (199.27 - 199.91) ms199.45 ± (199.13 - 199.76) ms-0.1%
process.time_to_main_ms74.31 ± (74.15 - 74.46) ms73.95 ± (73.85 - 74.05) ms-0.5%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed16.38 ± (16.36 - 16.41) MB16.35 ± (16.33 - 16.37) MB-0.2%
runtime.dotnet.threads.count20 ± (20 - 20)20 ± (20 - 20)+0.0%✅⬆️
.NET 6 - CallTarget+Inlining+NGEN
process.internal_duration_ms598.23 ± (595.81 - 600.66) ms597.44 ± (594.75 - 600.13) ms-0.1%
process.time_to_main_ms529.10 ± (528.03 - 530.16) ms526.35 ± (525.39 - 527.32) ms-0.5%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed61.63 ± (61.53 - 61.74) MB61.74 ± (61.65 - 61.84) MB+0.2%✅⬆️
runtime.dotnet.threads.count30 ± (30 - 31)30 ± (30 - 31)+0.1%✅⬆️
.NET 8 - Baseline
process.internal_duration_ms198.88 ± (198.55 - 199.21) ms197.21 ± (196.86 - 197.56) ms-0.8%
process.time_to_main_ms73.00 ± (72.84 - 73.16) ms72.55 ± (72.35 - 72.74) ms-0.6%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed11.69 ± (11.67 - 11.71) MB11.70 ± (11.67 - 11.72) MB+0.1%✅⬆️
runtime.dotnet.threads.count18 ± (18 - 19)18 ± (18 - 18)-0.4%
.NET 8 - Bailout
process.internal_duration_ms197.97 ± (197.59 - 198.34) ms196.80 ± (196.52 - 197.08) ms-0.6%
process.time_to_main_ms74.13 ± (73.97 - 74.28) ms73.75 ± (73.64 - 73.86) ms-0.5%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed11.72 ± (11.70 - 11.74) MB11.76 ± (11.74 - 11.79) MB+0.4%✅⬆️
runtime.dotnet.threads.count20 ± (19 - 20)19 ± (19 - 19)-1.4%
.NET 8 - CallTarget+Inlining+NGEN
process.internal_duration_ms518.67 ± (515.42 - 521.93) ms518.74 ± (515.68 - 521.79) ms+0.0%✅⬆️
process.time_to_main_ms489.68 ± (488.96 - 490.41) ms488.81 ± (488.00 - 489.61) ms-0.2%
runtime.dotnet.exceptions.count4 ± (4 - 4)4 ± (4 - 4)+0.0%
runtime.dotnet.mem.committed50.69 ± (50.66 - 50.73) MB50.72 ± (50.69 - 50.76) MB+0.1%✅⬆️
runtime.dotnet.threads.count30 ± (30 - 30)30 ± (30 - 30)-0.1%
Comparison explanation

Execution-time benchmarks measure the whole time it takes to execute a program, and are intended to measure the one-off costs. Cases where the execution time results for the PR are worse than latest master results are highlighted in **red**. The following thresholds were used for comparing the execution times:

  • Welch test with statistical test for significance of 5%
  • Only results indicating a difference greater than 5% and 5 ms are considered.

Note that these results are based on a single point-in-time result for each branch. For full results, see the dashboard.

Graphs show the p99 interval based on the mean and StdDev of the test run, as well as the mean value of the run (shown as a diamond below the graph).

Duration charts
FakeDbCommand (.NET Framework 4.8)
gantt
    title Execution time (ms) FakeDbCommand (.NET Framework 4.8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (72ms)  : 70, 75
    master - mean (72ms)  : 69, 75

    section Bailout
    This PR (8428) - mean (76ms)  : 74, 79
    master - mean (76ms)  : 74, 78

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (1,072ms)  : 1029, 1115
    master - mean (1,064ms)  : 1026, 1102

Loading
FakeDbCommand (.NET Core 3.1)
gantt
    title Execution time (ms) FakeDbCommand (.NET Core 3.1)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (113ms)  : 108, 118
    master - mean (112ms)  : 108, 115

    section Bailout
    This PR (8428) - mean (115ms)  : 111, 119
    master - mean (114ms)  : 111, 116

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (789ms)  : 763, 814
    master - mean (783ms)  : 764, 802

Loading
FakeDbCommand (.NET 6)
gantt
    title Execution time (ms) FakeDbCommand (.NET 6)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (100ms)  : 97, 103
    master - mean (99ms)  : 95, 103

    section Bailout
    This PR (8428) - mean (101ms)  : 98, 103
    master - mean (101ms)  : 98, 105

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (937ms)  : 896, 978
    master - mean (936ms)  : 904, 969

Loading
FakeDbCommand (.NET 8)
gantt
    title Execution time (ms) FakeDbCommand (.NET 8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (98ms)  : 94, 103
    master - mean (98ms)  : 95, 101

    section Bailout
    This PR (8428) - mean (98ms)  : 96, 101
    master - mean (99ms)  : 97, 101

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (812ms)  : 778, 845
    master - mean (814ms)  : 780, 848

Loading
HttpMessageHandler (.NET Framework 4.8)
gantt
    title Execution time (ms) HttpMessageHandler (.NET Framework 4.8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (201ms)  : 198, 205
    master - mean (201ms)  : 196, 205

    section Bailout
    This PR (8428) - mean (204ms)  : 201, 207
    master - mean (204ms)  : 201, 206

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (1,176ms)  : 1134, 1218
    master - mean (1,182ms)  : 1132, 1232

Loading
HttpMessageHandler (.NET Core 3.1)
gantt
    title Execution time (ms) HttpMessageHandler (.NET Core 3.1)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (290ms)  : 283, 296
    master - mean (288ms)  : 284, 292

    section Bailout
    This PR (8428) - mean (289ms)  : 286, 293
    master - mean (288ms)  : 285, 291

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (965ms)  : 943, 986
    master - mean (963ms)  : 936, 989

Loading
HttpMessageHandler (.NET 6)
gantt
    title Execution time (ms) HttpMessageHandler (.NET 6)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (283ms)  : 277, 289
    master - mean (283ms)  : 278, 288

    section Bailout
    This PR (8428) - mean (282ms)  : 278, 285
    master - mean (282ms)  : 277, 287

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (1,156ms)  : 1114, 1199
    master - mean (1,158ms)  : 1124, 1191

Loading
HttpMessageHandler (.NET 8)
gantt
    title Execution time (ms) HttpMessageHandler (.NET 8)
    dateFormat  x
    axisFormat %Q
    todayMarker off
    section Baseline
    This PR (8428) - mean (280ms)  : 275, 284
    master - mean (282ms)  : 277, 287

    section Bailout
    This PR (8428) - mean (281ms)  : 278, 284
    master - mean (282ms)  : 276, 288

    section CallTarget+Inlining+NGEN
    This PR (8428) - mean (1,040ms)  : 996, 1085
    master - mean (1,041ms)  : 990, 1092

Loading

@anna-git anna-git added area:native-library Automatic instrumentation native C++ code (Datadog.Trace.ClrProfiler.Native) labels Apr 10, 2026
## Summary of changes

This reproduces the crash [described in this
README](https://github.com/DataDog/dd-trace-dotnet/blob/82cc4cf0e29478fd2fdc41afdf764a2abf662199/repro/APMS-19196/README.md)
on linux x64 arch.

Aim is to merge to #8428
First tested it's crashing on master 
<img width="2830" height="851" alt="image"
src="https://github.com/user-attachments/assets/96e882fa-308e-44b6-8116-c93c7d5b7bb2"
/>


## Reason for change

## Implementation details

## Test coverage

## Other details
<!-- Fixes #{issue} -->


<!--  ⚠️ Note:

Where possible, please obtain 2 approvals prior to merging. Unless
CODEOWNERS specifies otherwise, for external teams it is typically best
to have one review from a team member, and one review from apm-dotnet.
Trivial changes do not require 2 reviews.

MergeQueue is NOT enabled in this repository. If you have write access
to the repo, the PR has 1-2 approvals (see above), and all of the
required checks have passed, you can use the Squash and Merge button to
merge the PR. If you don't have write access, or you need help, reach
out in the #apm-dotnet channel in Slack.
-->
@github-actions
Copy link
Copy Markdown
Contributor

Snapshots difference summary

The following differences have been observed in committed snapshots. It is meant to help the reviewer.
The diff is simplistic, so please check some files anyway while we improve it.

3 occurrences of :

+  },
+  {
+    TraceId: Id_1,
+    SpanId: Id_62,
+    Name: trace.annotation,
+    Resource: ExtremeExceptionHandling.DeepNestedExceptionHandlingSync,
+    Service: Samples.TraceAnnotations,
+    ParentId: Id_2,
+    Tags: {
+      component: trace,
+      env: integration_tests,
+      language: dotnet,
+      version: 1.0.0
+    }

3 occurrences of :

+  },
+  {
+    TraceId: Id_1,
+    SpanId: Id_62,
+    Name: trace.annotation,
+    Resource: ExtremeExceptionHandling.DeepNestedExceptionHandlingSync,
+    Service: Samples.TraceAnnotations.VersionMismatch.AfterFeature,
+    ParentId: Id_2,
+    Tags: {
+      component: trace,
+      env: integration_tests,
+      language: dotnet,
+      version: 1.0.0
+    }

3 occurrences of :

+  },
+  {
+    TraceId: Id_1,
+    SpanId: Id_62,
+    Name: trace.annotation,
+    Resource: ExtremeExceptionHandling.DeepNestedExceptionHandlingSync,
+    Service: Samples.TraceAnnotations.VersionMismatch.BeforeFeature,
+    ParentId: Id_2,
+    Tags: {
+      component: trace,
+      env: integration_tests,
+      language: dotnet,
+      version: 1.0.0
+    }

@bouwkast bouwkast added the AI Generated Largely based on code generated by an AI or LLM. This label is the same across all dd-trace-* repos label Apr 10, 2026
Add original index as final tiebreaker so std::sort does not
reorder catch/filter handlers that share the same try region.
Without this, multiple catch blocks for the same try can be
silently swapped, changing which handler the runtime evaluates
first.
Extract IsProperlyContained helper, use explicit types, add braces
on all control flow, and use named variables in the sort comparator
to match surrounding native code style.
@bouwkast bouwkast marked this pull request as ready for review April 13, 2026 14:59
@bouwkast bouwkast requested review from a team as code owners April 13, 2026 14:59
@bouwkast bouwkast requested a review from link04 April 13, 2026 14:59
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6b6b9a4b4b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +325 to +328
std::sort(clauses, clauses + 5, [](const EHClause& a, const EHClause& b) {
return a.m_pTryBegin->m_offset > b.m_pTryBegin->m_offset &&
a.m_pTryEnd->m_offset < b.m_pTryEnd->m_offset;
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Remove undefined comparator from regression test

OldComparatorFailsMiddlewareScenario calls std::sort with a comparator that is not a strict weak ordering, so the resulting order is undefined by the C++ standard; on different STL implementations or optimization levels, new3Index can legitimately end up before orig1Index, making this test flaky even when production code is correct. Please make this regression deterministic (for example by asserting pairwise comparator behavior directly, or by validating the old logic without invoking std::sort).

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is testing the old behavior that we won't have anymore, we proved it was failing, but maybe we could remove this test?

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes EH clause ordering in ILRewriter::Export() to correctly handle clauses whose try region is nested inside another clause’s handler region, preventing CLR InvalidProgramException during JIT validation (APMS-19196).

Changes:

  • Replaces the previous EH std::sort comparator with ILRewriter::SortEHClauses, sorting by computed nesting depth (try-in-try and try-in-handler) with a strict weak ordering.
  • Adds native unit tests for EH sorting plus a managed “extreme EH” integration scenario to reproduce the crash.
  • Updates integration test expectations/snapshots to account for the additional traced method.

Reviewed changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tracer/src/Datadog.Tracer.Native/il_rewriter.cpp Uses new SortEHClauses in Export() and implements depth-based EH sorting.
tracer/src/Datadog.Tracer.Native/il_rewriter.h Declares ILRewriter::SortEHClauses for reuse/unit testing.
tracer/test/Datadog.Tracer.Native.Tests/il_rewriter_eh_sort_test.cpp Adds gtest coverage for try-in-try and try-in-handler ordering, including a repro of the old comparator failure.
tracer/test/Datadog.Tracer.Native.Tests/Datadog.Tracer.Native.Tests.vcxproj Includes the new native test source in the VS project.
tracer/test/Datadog.Tracer.Native.Tests/Datadog.Tracer.Native.Tests.vcxproj.filters Adds the new native test source to filters for VS organization.
tracer/test/Datadog.Tracer.Native.Tests/CMakeLists.txt Includes the new test source in the CMake test target.
tracer/test/test-applications/integrations/Samples.TraceAnnotations/ExtremeExceptionHandling.cs Adds a managed method with deep EH nesting used as a regression repro.
tracer/test/test-applications/integrations/Samples.TraceAnnotations/ProgramHelpers.cs Executes the new extreme EH scenario as part of the sample run.
tracer/test/test-applications/integrations/Samples.TraceAnnotations.VersionMismatch.BeforeFeature/Samples.TraceAnnotations.VersionMismatch.BeforeFeature.csproj Ensures the new managed file is compiled into the version-mismatch sample.
tracer/test/test-applications/integrations/Samples.TraceAnnotations.VersionMismatch.AfterFeature/Samples.TraceAnnotations.VersionMismatch.AfterFeature.csproj Ensures the new managed file is compiled into the version-mismatch sample.
tracer/test/Datadog.Trace.ClrProfiler.IntegrationTests/TraceAnnotationsTests.cs Updates expected span count and sets DD_TRACE_METHODS to trace the new sync repro method.
tracer/test/snapshots/TraceAnnotationsAutomaticOnlyTests._.Net.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsAutomaticOnlyTests._.DotNet.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsAutomaticOnlyTests._.Core.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchAfterFeatureTests._.Net.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchAfterFeatureTests._.DotNet.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchAfterFeatureTests._.Core.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchBeforeFeatureTests._.Net.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchBeforeFeatureTests._.DotNet.verified.txt Snapshot updated for added span from the extreme EH method.
tracer/test/snapshots/TraceAnnotationsVersionMismatchBeforeFeatureTests._.Core.verified.txt Snapshot updated for added span from the extreme EH method.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +1 to +14
#include "pch.h"

#include "../../src/Datadog.Tracer.Native/il_rewriter.h"

// Helper to build a doubly-linked chain of ILInstr nodes with specified offsets.
// Returns a heap-allocated array; the caller must delete[].
// Each node's m_pNext and m_pPrev are wired up in sequence. The last node's
// m_pNext points to a sentinel (the first node acts as its own sentinel for
// handler-end calculations via m_pHandlerEnd->m_pNext).
static ILInstr* MakeInstrChain(const std::vector<unsigned>& offsets)
{
auto n = offsets.size();
auto* instrs = new ILInstr[n];
memset(instrs, 0, n * sizeof(ILInstr));
Copy link

Copilot AI Apr 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test file uses std::vector, std::sort, and memset but does not include the corresponding standard headers. With the current pch.h (only gtest + CLR headers), this will not compile on a clean build. Add explicit includes for the headers you use (e.g., , , ).

Copilot uses AI. Check for mistakes.
Comment on lines +5 to +21
// Helper to build a doubly-linked chain of ILInstr nodes with specified offsets.
// Returns a heap-allocated array; the caller must delete[].
// Each node's m_pNext and m_pPrev are wired up in sequence. The last node's
// m_pNext points to a sentinel (the first node acts as its own sentinel for
// handler-end calculations via m_pHandlerEnd->m_pNext).
static ILInstr* MakeInstrChain(const std::vector<unsigned>& offsets)
{
auto n = offsets.size();
auto* instrs = new ILInstr[n];
memset(instrs, 0, n * sizeof(ILInstr));
for (size_t i = 0; i < n; i++)
{
instrs[i].m_offset = offsets[i];
instrs[i].m_pPrev = (i > 0) ? &instrs[i - 1] : &instrs[n - 1];
instrs[i].m_pNext = (i < n - 1) ? &instrs[i + 1] : &instrs[0];
}
return instrs;
Copy link

Copilot AI Apr 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MakeInstrChain builds a circular list (last->next points back to the first node), but the comment describes a sentinel node for handler-end calculations. This can be misleading, and it also doesn’t model ILRewriter’s real list where the last instruction’s m_pNext points to a dedicated sentinel with m_offset == code size (important when a handler ends at the end of the method). Consider either updating the comment to reflect the circular list, or creating an explicit sentinel node in the helper to better match production semantics.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Collaborator

@NachoEchevarria NachoEchevarria left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

Copy link
Copy Markdown
Contributor

@anna-git anna-git left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a few comments, after trying to wrap my head around it 😅
From what I understand, the new algorithm does:

  1. calculate depth of each exception handling clause
  2. create a blank array the size of the clauses
  3. compare eh clause's depth 2 by 2 and reorder indices according to it
    a. if they have different depths, sort the new indices array according to it, putting the deeper depth first (ecma rule)
    b. if depths are the same, either sort by try begin offset
    c. either the offsets are the same, then just keep the original order

// All values are IL offsets using exclusive ends (first offset past the region).
static bool IsProperlyContained(unsigned innerBegin, unsigned innerEnd, unsigned outerBegin, unsigned outerEnd)
{
bool contained = innerBegin >= outerBegin && innerEnd <= outerEnd;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT with early exit

Suggested change
bool contained = innerBegin >= outerBegin && innerEnd <= outerEnd;
bool identical = innerBegin == outerBegin && innerEnd == outerEnd;
if (identical)
{
return false;
}
bool contained = innerBegin >= outerBegin && innerEnd <= outerEnd;
return contained;

}

std::sort(indices.get(), indices.get() + nEH, [&](unsigned a, unsigned b) {
if (depth[a] != depth[b])
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (depth[a] != depth[b])
// Primary (inner try first): e.g. try { try { } catch { } } catch { }
if (depth[a] != depth[b])

return depth[a] > depth[b];
}

unsigned offsetA = pEH[a].m_pTryBegin->m_offset;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
unsigned offsetA = pEH[a].m_pTryBegin->m_offset;
// Secondary (same depth, different tries — order by try start offset): e.g.
// try { } catch { } try { } catch { }
unsigned offsetA = pEH[a].m_pTryBegin->m_offset;


// Preserve original order for clauses with equal depth and try offset
// (e.g. multiple catch handlers for the same try block).
return a < b;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return a < b;
// Tertiary (same try — keep compiler order): e.g. try { } catch (A) { } catch (B) { }
return a < b;

Comment on lines +325 to +328
std::sort(clauses, clauses + 5, [](const EHClause& a, const EHClause& b) {
return a.m_pTryBegin->m_offset > b.m_pTryBegin->m_offset &&
a.m_pTryEnd->m_offset < b.m_pTryEnd->m_offset;
});
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is testing the old behavior that we won't have anymore, we proved it was failing, but maybe we could remove this test?

#include "pch.h"

#include "../../src/Datadog.Tracer.Native/il_rewriter.h"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot complaining about this:

Suggested change
#include <cstring>
#include <vector>

Comment on lines +7 to +9
// Each node's m_pNext and m_pPrev are wired up in sequence. The last node's
// m_pNext points to a sentinel (the first node acts as its own sentinel for
// handler-end calculations via m_pHandlerEnd->m_pNext).
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Each node's m_pNext and m_pPrev are wired up in sequence. The last node's
// m_pNext points to a sentinel (the first node acts as its own sentinel for
// handler-end calculations via m_pHandlerEnd->m_pNext).
// For simplicity, nodes are linked in a ring (last points to first). This is not production IL layout; it avoids a separate sentinel while keeping every node with a valid successor.
// SortEHClauses uses m_pHandlerEnd->m_pNext->m_offset as the exclusive end of a handler region (same convention as ILRewriter::ImportEH).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

AI Generated Largely based on code generated by an AI or LLM. This label is the same across all dd-trace-* repos area:native-library Automatic instrumentation native C++ code (Datadog.Trace.ClrProfiler.Native)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants